import { app, protocol, BrowserWindow, ipcMain, shell, Menu, Tray, globalShortcut, nativeTheme, screen } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import fs from 'fs';
import path from 'path';
import shortcut from 'windows-shortcuts';
import resolveLnk from '@recent-cli/resolve-lnk';
import getWindowsShortcutProperties from 'get-windows-shortcut-properties';
import lodash from 'lodash';

import logger from './utils/logger';
import systemutil from './utils/systemutil';
import secureStore from './utils/secureStore';
import setupAutoLaunch from './utils/autoLaunch';
import Result from './utils/result';
import base64ToImg from './utils/base64ToImg';
import downloadWin from './utils/downloadManager';
import InstallSoftware from './utils/installSoftware';

const { createDownload, pauseDownload, resumeDownload, cancelDownload } = downloadWin;
const { debounce } = lodash;
const isSingleInstance = app.requestSingleInstanceLock();
const { systemInfo, cpuInfo, memInfo, graphInfo, osInfo, diskInfo, fsInfo, networkInfo, loadInfo, proceInfo, installedAppsInfo } = systemutil;
const { baseSave, readBase, isOnBase } = base64ToImg;
const isDevelopment = process.env.NODE_ENV !== 'production'
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])
const appPath = process.execPath; // 获取当前应用的路径
let win;
let downloadWindow = null;
let _tray = null
let iconExtractor;

async function createWindow() {
  let icoFilePath = path.join(__dirname, '../public/favicon.ico');
  logger.info('icoFilePath: ' + icoFilePath);
  Menu.setApplicationMenu(null);
  nativeTheme.themeSource = secureStore.getPlain('colorMode') == 'light' ? 'dark' : 'light';
  logger.info('themeSource: ' + secureStore.getPlain('colorMode'));
  win = new BrowserWindow({
    width: secureStore.getPlain('loadWidth'),
    height: secureStore.getPlain('loadHeight'),
    minWidth: 1065,
    minHeight: 680,
    icon: icoFilePath, // 设置窗口图标
    frame: false, // 👈 设置为 false 去掉默认的标题栏和边框
    resizable: true, // 启用调整大小功能
    movable: true, // ✅ 允许拖动和鼠标事件
    webPreferences: {
      contextIsolation: false,
      nodeIntegration: true,
      enableRemoteModule: false
    }
  })
  // 注册快捷键 F12 打开调试工具
  const devToolsShortcut = process.platform === 'darwin' ? 'Alt+Command+I' : 'Control+Shift+I';
  // 确保在 app.whenReady() 后调用
  if (!app.isReady()) {
    app.once('ready', () => {
      logger.info('app ready');
      CloseIconExtractorDestroy();
      globalShortcut.register(devToolsShortcut, () => {
        if (win && !win.isDestroyed()) {
          win.webContents.toggleDevTools();
        }
      });
    });
  } else {
    globalShortcut.register(devToolsShortcut, () => {
      if (win && !win.isDestroyed()) {
        win.webContents.toggleDevTools();
      }
    });
  }
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
  } else {
    createProtocol('app')
    win.loadURL('app://./index.html')
  }
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '打开下载中心',
      click: () => {
        createDownloadWindow();
      }
    },
    { label: '显示', click: () => win.show() },
    {
      label: '退出', click: () => {
        app.isQuitting = true;
        CloseIconExtractorDestroy();
        const windows = BrowserWindow.getAllWindows();
        windows.forEach(wi => wi.destroy()); // 强制关闭窗口
        app.quit();
      }
    },
  ]);
  // 创建托盘图标
  _tray = new Tray(icoFilePath); // 替换为你自己的图标路径
  //图标标头
  _tray.setToolTip('Soft Management');
  // 鼠标左键点击托盘图标时恢复窗口
  _tray.on('click', (event, bounds) => {
    if (win.isVisible()) {
      win.hide(); // 如果窗口已经可见，则隐藏
    } else {
      win.show(); // 如果窗口不可见，则显示
    }
  });
  // 鼠标右键点击托盘图标时显示上下文菜单
  _tray.setContextMenu(contextMenu);

  // 拦截关闭事件
  win.on('close', (event) => {
    if (!app.isQuitting) {
      event.preventDefault(); // 阻止默认的关闭行为
      win.hide(); // 隐藏窗口
    }
  });
  // 窗口正在最大化
  win.on('maximize', () => {
    win.webContents.send('update-maximize-status', true);
  });
  //窗口正在还原
  win.on('unmaximize', () => {
    win.webContents.send('update-maximize-status', false);
  });
  if (secureStore.getPlain('isMaximized') == 'true') {
    logger.info("窗口最大化")
    win.maximize();
  }
  //窗口大小变化时通知前端
  //let lastResizeTime = 0;
  //const RESIZE_DEBOUNCE_INTERVAL = 30; // 时间间隔阈值，单位毫秒
  win.on('resize', debounce(() => {
    //const now = Date.now();
    //if (now - lastResizeTime > RESIZE_DEBOUNCE_INTERVAL) {
    //  lastResizeTime = now;
    const [width, height] = win.getSize();
    logger.info('resize, isMaximized: ' + win.isMaximized());
    secureStore.setPlain('winWidth', width);
    secureStore.setPlain('winHeight', height);
    win.webContents.send('window-resized', { width, height });
    if (!win.isMaximized()) {
      secureStore.setPlain('loadWidth', width);
      secureStore.setPlain('loadHeight', height);
    }
    //}
  }, 300));
}
//walkDir('C:/LAN/Work/Electron/my-electron-vue-app/slide');
// 递归遍历函数
function walkDir(dir) {
  // 支持的图片格式
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.ico', '.svg'];
  const files = fs.readdirSync(dir);
  files.forEach(file => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    if (stat.isDirectory()) {
      // 递归处理子目录
      walkDir(filePath);
    } else if (stat.isFile()) {
      // 检查文件扩展名是否为图片格式
      const ext = path.extname(file).toLowerCase();
      if (imageExtensions.includes(ext)) {
        compressImageFile(filePath);
      }
    }
  });
}
// 启用开机启动
function enableAutoLaunch() {
  setupAutoLaunch().then(() => logger.info(`Auto launch enabled`)).catch(err => logger.error(`Failed to disable auto launch: ${err}`));
}
app.isQuitting = false;
if (!isSingleInstance) {
  app.quit();
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当尝试启动第二个实例时，聚焦到已存在的窗口
    if (win) {
      if (win.isMinimized()) win.restore();
      win.focus();
    }
  });
  //主窗体加载
  app.whenReady().then(async () => {
    if (appPath.indexOf('node_modules') == -1) {
      enableAutoLaunch(); // 在应用启动时启用开机启动
    }
    await createWindow();
    win.webContents.on('did-finish-load', async () => {
      //加载完毕
      app.on('activate', async () => {
        if (BrowserWindow.getAllWindows().length === 0) {
          await createWindow();
        } else {
          // 在macOS上，点击Dock图标时重新打开窗口
          win.show();
        }
      });
    });
    await createDownloadWindow();
  });
  //主窗体关闭时退出应用
  app.on('window-all-closed', () => {
    logger.info('app window-all-closed');
    CloseIconExtractorDestroy();
    if (process.platform !== 'darwin') app.quit();
  });
}
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
//错误处理
process.on('uncaughtException', (error) => {
  logger.error(`Uncaught Exception: ${error.message}`);
  logger.error(error.stack);
});
//错误处理
process.on('unhandledRejection', (reason, promise) => {
  logger.error(`Unhandled Rejection at: ${promise}, reason: ${reason}`);
});

// 处理请求最小化窗口
ipcMain.on('minimize-window', () => {
  win.minimize();
});
// 处理切换最大化/还原窗口
ipcMain.on('toggle-maximize', () => {
  try {
    if (win.isMaximized()) {
      secureStore.setPlain('isMaximized', false);
      win.restore();
    } else {
      secureStore.setPlain('isMaximized', true);
      win.maximize();
    }
  } catch (error) {
    logger.error(error);
  }
});
// 处理请求关闭窗口
ipcMain.on('close-window', () => {
  win.hide();
});
// 处理请求最大化状态
ipcMain.on('request-maximize-status', (event) => {
  if (win) {
    event.reply('update-maximize-status', win.isMaximized());
  }
});
//获取初始化值
ipcMain.handle('win-load', (event) => {
  return new Promise((resolve, reject) => {
    try {
      resolve(Result.success({ winWidth: secureStore.getPlain('winWidth'), winHeight: secureStore.getPlain('winHeight'), isMaximized: secureStore.getPlain('isMaximized'), colorMode: secureStore.getPlain('colorMode') }));
    } catch (error) {
      reject(Result.error(101, error.message));
    }
  });
});
//通过 IPC 获取 Base64 图片数据
ipcMain.handle('read-image-file', async (event, filePath) => {
  try {
    const imgPath = path.join(__dirname, filePath);
    if (fs.existsSync(imgPath)) {
      const data = fs.readFileSync(imgPath);
      return `data:image/jpeg;base64,${Buffer.from(data).toString('base64')}`;
    }
    logger.info(`读取图片失败: ${imgPath}`);
    return null;
  } catch (error) {
    logger.error(`读取图片失败: ${error.message}`);
    return null;
  }
});
// 压缩图片
async function compressImageFile(filePath, iconJimp = {}) {
  logger.info('执行压缩图片: ' + filePath);
  try {
    // 详细检查输入文件
    logger.info('检查输入文件路径: ' + filePath);
    logger.info('文件是否存在: ' + fs.existsSync(filePath));

    if (!fs.existsSync(filePath)) {
      logger.warn('输入图片文件不存在: ' + filePath);
      return;
    }

    // 检查文件是否可读
    try {
      fs.accessSync(filePath, fs.constants.R_OK);
      logger.info('输入文件可读');
    } catch (accessError) {
      logger.error('输入文件不可读: ' + accessError.message);
      return;
    }

    // 确保输出目录存在
    const outputDir = path.dirname(filePath);
    logger.info('输出目录: ' + outputDir);
    if (!fs.existsSync(outputDir)) {
      try {
        fs.mkdirSync(outputDir, { recursive: true });
        logger.info('创建输出目录成功');
      } catch (mkdirError) {
        logger.error('创建输出目录失败: ' + mkdirError.message);
        return;
      }
    }

    // 获取配置参数并设置默认值
    logger.info('iconJimp 配置: ' + JSON.stringify(iconJimp));

    // 记录原始文件大小
    let originalStats;
    try {
      originalStats = fs.statSync(filePath);
      logger.info('原始文件大小: ' + originalStats.size + ' bytes');
    } catch (statError) {
      logger.error('无法获取原始文件大小:', statError.message);
      originalStats = { size: 0 };
    }

    logger.info('使用 jimp 进行图片压缩');
    try {
      const Jimp = await import('jimp');

      const image = await Jimp.default.read(filePath);
      logger.info('图片读取成功，原始尺寸: ' + image.bitmap.width + 'x' + image.bitmap.height);

      // 处理 iconJimp 配置
      if (!iconJimp || Object.keys(iconJimp).length === 0) {
        // 如果没有提供配置，使用图片原始尺寸
        iconJimp = {
          width: image.bitmap.width,
          height: image.bitmap.height,
          quality: 60
        };
        logger.info('使用图片原始尺寸作为默认参数');
      } else {
        // 确保参数有合理默认值
        iconJimp.width = iconJimp.width || image.bitmap.width;
        iconJimp.height = iconJimp.height || image.bitmap.height;
        iconJimp.quality = iconJimp.quality || 60;
      }

      logger.info('最终压缩参数:', JSON.stringify(iconJimp));

      // 创建临时文件路径
      const tempFilePath = filePath + '.tmp';

      await image
        .scaleToFit(iconJimp.width, iconJimp.height)
        .quality(iconJimp.quality)
        .writeAsync(tempFilePath);

      // 检查压缩结果
      if (fs.existsSync(tempFilePath)) {
        try {
          const compressedStats = fs.statSync(tempFilePath);
          logger.info('处理后文件大小: ' + compressedStats.size + ' bytes');
          if (originalStats.size > 0) {
            if (compressedStats.size > originalStats.size) {
              const increaseRatio = ((compressedStats.size - originalStats.size) / originalStats.size * 100).toFixed(2);
              logger.info('文件增大: ' + increaseRatio + '% (可能因为尺寸放大或格式优化)');
              // 删除增大的临时文件，保留原始文件
              fs.unlinkSync(tempFilePath);
              logger.info('保留原始文件，删除增大的处理文件');
            } else if (compressedStats.size < originalStats.size) {
              const compressionRatio = ((originalStats.size - compressedStats.size) / originalStats.size * 100).toFixed(2);
              logger.info('压缩率: ' + compressionRatio + '%');
              // 用压缩后的文件替换原始文件
              fs.unlinkSync(filePath);
              fs.renameSync(tempFilePath, filePath);
            } else {
              logger.info('文件大小无变化');
              // 删除临时文件
              fs.unlinkSync(tempFilePath);
            }
          } else {
            // 无法获取原始文件大小时，直接替换
            fs.unlinkSync(filePath);
            fs.renameSync(tempFilePath, filePath);
          }
        } catch (compressedStatError) {
          logger.error('无法获取处理后文件大小:', compressedStatError.message);
          // 出错时删除临时文件
          if (fs.existsSync(tempFilePath)) {
            fs.unlinkSync(tempFilePath);
          }
        }
      } else {
        logger.error('压缩后的文件未创建');
      }

      logger.info('使用 jimp 图片压缩完成');
    } catch (jimpError) {
      logger.error('jimp 图片压缩失败:', jimpError.message);
      logger.error('jimp 错误详情:', jimpError.stack);
    }
  } catch (error) {
    logger.error('图片压缩异常: ' + error.message);
    logger.error('错误堆栈: ' + error.stack);
  }
}
//点击打开进程
ipcMain.handle('onclick-exe', async (event, exePath) => {
  return new Promise((resolve, reject) => {
    if (fs.existsSync(exePath)) {
      // 打开解析出来的目标路径
      shell.openPath(exePath)
        .then(() => {
          resolve(Result.success());
        })
        .catch(error => {
          reject(Result.error(101, error.message));
        });
    } else {
      reject(Result.error(101, `路径不存在: ${exePath}`));
    }
  });
});
//页面修改主题
ipcMain.handle('update-dark-mode:web', () => {
  if (nativeTheme.shouldUseDarkColors) {
    nativeTheme.themeSource = 'light';
    secureStore.setPlain('colorMode', "dark");//浅色
  } else {
    nativeTheme.themeSource = 'dark';
    secureStore.setPlain('colorMode', "light");//深色
  }
  return nativeTheme.shouldUseDarkColors;
});
//拖拽lnk
ipcMain.handle('get-icon', async (event, fileName, filePath) => {
  logger.info('获取lnk/exe图标: ' + fileName + ' ' + filePath);
  try {
    // 检查缓存图标 - 只有当fileName有效时才检查
    if (fileName && typeof fileName === 'string') {
      let softIcon = secureStore.getPlain("softIcon");
      if (softIcon && Array.isArray(softIcon)) {
        const row = softIcon.filter(p => p.name && (fileName.toLowerCase().indexOf(p.name.toLowerCase()) > -1 || p.name.toLowerCase().indexOf(fileName.toLowerCase()) > -1));
        if (row.length > 0) {
          return Result.success({
            exePath: filePath,
            iconBase64: row[0].icon.replace(/^data:image\/\w+;base64,/, '')
          });
        }
      }
    }

    // 添加参数验证
    if (!filePath || typeof filePath !== 'string') {
      logger.error('文件路径无效: ' + filePath);
      return Result.error(101, '文件路径无效');
    }
    const baseName = path.basename(fileName, path.extname(fileName));
    if (isOnBase(baseName)) {
      let icoData = await readBase(baseName);
      if (icoData.code == 200) {
        baseSave(baseName, icoData.data);
        return Result.success({
          exePath: filePath,
          iconBase64: icoData.data
        });
      }
    }
    let lnkData = null;
    if (filePath.toLowerCase().endsWith('.lnk')) {
      try {
        lnkData = await getLnkExe(filePath);
      } catch (error) {
        return Result.error(101, `快捷方式解析失败: ${error.message}`);
      }
      if (!lnkData.exe) return Result.error(101, '无效的 exe 路径');
      if (lnkData.ico) {
        if (lnkData.ico.toLowerCase().endsWith('.ico')) {
          logger.info(JSON.stringify(lnkData));
          let iconPath;
          if (lnkData.ico.includes('%')) {
            iconPath = await resolveEnvPath(lnkData.ico);
          } else {
            iconPath = lnkData.ico;
          }
          if (fs.existsSync(iconPath)) {
            const iconBase64 = Buffer.from(fs.readFileSync(iconPath)).toString('base64');
            baseSave(baseName, iconBase64);
            return Result.success({
              exePath: lnkData.exe,
              iconBase64: iconBase64
            });
          } else {
            logger.error(`图标文件不存在: ${iconPath}`);
          }
        }
      }
    } else if (filePath.toLowerCase().endsWith('.exe')) {
      lnkData = { exe: filePath }
    }
    logger.info(`lnkData: ${JSON.stringify(lnkData)}`);
    // 👇 每次都销毁旧实例
    CloseIconExtractorDestroy()
    // 👇 强制重新 require，避免复用旧子进程
    delete require.cache[require.resolve('icon-extractor')];
    process.env.ICON_EXTRACTOR_PATH = getIconExtractorPath();
    iconExtractor = require('icon-extractor');
    iconExtractor.emitter.removeAllListeners('icon');

    return new Promise((resolve, reject) => {
      const onIcon = (data) => {
        iconExtractor.emitter.removeListener('icon', onIcon);
        baseSave(baseName, data.Base64ImageData);
        resolve(data !== null && data !== undefined ? Result.success({ exePath: lnkData.exe, iconBase64: data.Base64ImageData }) : Result.error());
      };
      iconExtractor.emitter.once('icon', onIcon);
      iconExtractor.getIcon(baseName, lnkData.exe, (error, data) => {
        iconExtractor.emitter.removeListener('icon', onIcon);
        if (error) {
          reject(Result.error(101, error.message));
        } else {
          baseSave(baseName, data.Base64ImageData);
          resolve(data !== null && data !== undefined ? Result.success({ exePath: lnkData.exe, iconBase64: data.Base64ImageData }) : Result.error());
        }
      });
      // 设置超时机制防止卡死
      setTimeout(() => {
        reject(Result.error(101, '图标提取超时'));
      }, 5000);
    });
  } catch (error) {
    logger.error(`get-icon: ${error.message}`);
    return Result.error(101, 'Failed to extract icon');
  }
});
//拖拽exe
ipcMain.handle('get-exe-icon', async (event, fileName, filePath) => {
  logger.info('拖拽exe获取图标: ' + fileName + ' ' + filePath)
  try {
    // 检查缓存图标 - 只有当fileName有效时才检查
    if (fileName && typeof fileName === 'string') {
      let softIcon = secureStore.getPlain("softIcon");
      if (softIcon && Array.isArray(softIcon)) {
        const row = softIcon.filter(p => p.name && fileName.toLowerCase().indexOf(p.name.toLowerCase()) > -1);
        if (row.length > 0) {
          return Result.success({
            exePath: filePath,
            iconBase64: row[0].icon.replace(/^data:image\/\w+;base64,/, '')
          });
        }
      }
    }

    // 添加参数验证
    if (!filePath || typeof filePath !== 'string') {
      logger.error('文件路径无效: ' + filePath);
      return Result.error(101, '文件路径无效');
    }
    const baseName = path.basename(fileName, path.extname(fileName));
    if (isOnBase(baseName)) {
      let icoData = await readBase(baseName);
      if (icoData.code == 200) {
        return Result.success({
          exePath: filePath,
          iconBase64: icoData.data
        });
      }
    }
    let lnkData = { exe: filePath };
    // 👇 每次都销毁旧实例
    CloseIconExtractorDestroy()
    // 👇 强制重新 require，避免复用旧子进程
    delete require.cache[require.resolve('icon-extractor')];
    process.env.ICON_EXTRACTOR_PATH = getIconExtractorPath();
    iconExtractor = require('icon-extractor');
    iconExtractor.emitter.removeAllListeners('icon');
    return new Promise((resolve, reject) => {
      const onIcon = (data) => {
        iconExtractor.emitter.removeListener('icon', onIcon);
        baseSave(baseName, data.Base64ImageData);
        resolve(data !== null && data !== undefined ? Result.success({ exePath: lnkData.exe, iconBase64: data.Base64ImageData }) : Result.error());
      };
      iconExtractor.emitter.once('icon', onIcon);
      iconExtractor.getIcon(baseName, lnkData.exe, (error, data) => {
        iconExtractor.emitter.removeListener('icon', onIcon);
        if (error) {
          reject(Result.error(101, error.message));
        } else {
          baseSave(baseName, data.Base64ImageData);
          resolve(data !== null && data !== undefined ? Result.success({ exePath: lnkData.exe, iconBase64: data.Base64ImageData }) : Result.error());
        }
      });
      // 设置超时机制防止卡死
      setTimeout(() => {
        reject(Result.error(101, '图标提取超时'));
      }, 5000);
    });
  } catch (error) {
    logger.error(`'get-exe-icon: ${error.message}`);
    return Result.error(101, 'Failed to extract icon');
  }
});
//lnk文件获取实际进程地址
function getLnkExe(filePath) {
  return new Promise(async (resolve, reject) => {
    if (process.platform !== 'win32') {
      return reject(new Error('仅支持 Windows 系统'));
    }

    if (!fs.existsSync(filePath)) {
      return reject(new Error(`文件不存在: ${filePath}`));
    }

    try {
      const result = shell.readShortcutLink(filePath);
      if (result.icon) {
        return resolve({ exe: result.target, ico: result.icon });
      }
      return resolve({ exe: result.target });
    } catch (errElectron) {
      logger.error('Electron shell.readShortcutLink 失败，尝试使用 windows-shortcuts...');
    }
    try {
      const target = await resolveLnk(filePath);
      return resolve({ exe: target });
    } catch (errResolveLnk) {
      logger.error('resolveLnk 失败，尝试使用 windows-shortcuts...');
    }
    if (process.platform === 'win32') {
      const output = await getWindowsShortcutProperties.sync(filePath);
      if (output) {
        return resolve({ exe: output[0].TargetPath });
      } else {
        logger.error('There was an error');
      }
    }
    shortcut.query(filePath, (error, details) => {
      if (error) {
        return reject(new Error(`无法解析快捷方式: ${error.message}`));
      }
      return resolve({ exe: details.target });
    });
  });
}
//保存快捷方式
ipcMain.handle('save-link', async (event, fileName, filePath) => {
  logger.info('保存快捷方式: ' + fileName + ' ' + filePath);
  let _data = secureStore.getPlain('linkList');
  _data.push({
    fileName: fileName,
    filePath: filePath
  });
  secureStore.setPlain('linkList', _data);
});
//删除快捷方式
ipcMain.handle('del-link', async (event, fileName) => {
  let _data = secureStore.getPlain('linkList');
  _data = _data.filter(item => item.fileName != fileName);
  secureStore.setPlain('linkList', _data)
});
//加载快捷方式
ipcMain.handle('get-links', async (event) => {
  let _data = secureStore.getPlain('linkList');
  return new Promise(async (resolve, reject) => {
    resolve(Result.success(_data));
  });
});
//关于我们HTML
ipcMain.handle('about-info', async (event) => {
  return new Promise(async (resolve, reject) => {
    resolve(Result.success(`<div>公司名称：xxxxx</div><div>公司地址：xxxxx</div>`));
  });
});
//解析环境变量路径
async function resolveEnvPath(envPath) {
  logger.info(`解析路径: ${envPath}`);
  // 查找路径中的环境变量部分
  const envVarMatch = envPath.match(/%([^%]+)%/);
  if (!envVarMatch) {
    // 如果没有找到环境变量，则直接返回原路径
    logger.info(`无环境变量，返回路径: ${resolvedPath}`);
    return envPath;
  }

  const [fullMatch, envVarName] = envVarMatch;
  const envValue = process.env[envVarName];

  if (envValue === undefined) {
    return null; //new Error(`Environment variable ${envVarName} is not defined.`);
  }

  // 替换环境变量为实际值并返回完整路径
  const resolvedPath = path.resolve(envPath.replace(fullMatch, envValue));
  logger.info(`替换环境变量后，返回路径: ${resolvedPath}`);
  return resolvedPath;
}
// 获取 IconExtractor.exe 的正确路径
function getIconExtractorPath() {
  if (process.env.NODE_ENV === 'development') {
    // 开发环境中从 node_modules 获取
    return path.join(__dirname, '../node_modules/icon-extractor/bin/IconExtractor.exe');
  } else {
    // 生产环境中从 resources 获取
    try {
      // 尝试使用 process.resourcesPath
      const resourcePath = path.join(process.resourcesPath, 'bin/IconExtractor.exe');
      if (fs.existsSync(resourcePath)) {
        return resourcePath;
      }
    } catch (e) {
      logger.error('无法访问 process.resourcesPath:', e.message);
    }

    // 备用方案：使用相对路径
    return path.join(__dirname, '../bin/IconExtractor.exe');
  }
}
//销毁IconExtractor
function CloseIconExtractorDestroy() {
  if (iconExtractor && typeof iconExtractor.destroy === 'function') {
    iconExtractor.destroy();
  }
}
//系统信息
ipcMain.handle('system-info', (event, type) => {
  return new Promise(async (resolve, reject) => {
    try {
      switch (type) {
        case 'system':
          resolve(Result.success(await systemInfo()));
          break;
        case 'cpu':
          resolve(Result.success(await cpuInfo()));
          break;
        case 'mem':
          resolve(Result.success(await memInfo()));
          break;
        case 'graph':
          resolve(Result.success(await graphInfo()));
          break;
        case 'os':
          resolve(Result.success(await osInfo()));
          break;
        case 'disk':
          resolve(Result.success(await diskInfo()));
          break;
        case 'fs':
          resolve(Result.success(await fsInfo()));
          break;
        case 'network':
          resolve(Result.success(await networkInfo()));
          break;
        case 'load':
          resolve(Result.success(await loadInfo()));
          break;
        case 'proce':
          resolve(Result.success(await proceInfo()));
          break;
        case 'installed':
          resolve(Result.success(await installedAppsInfo()));
          break;
        default:
          reject(Result.error());
          break;
      }
    } catch (error) {
      reject(Result.error(101, error.message));
    }
  });
});
// 监听下载状态更新事件
ipcMain.handle('download-status', (event, data) => {
  logger.info(`下载状态更新: ${JSON.stringify(data)}`);
  // 将下载状态转发给主窗口
  if (win && !win.isDestroyed()) {
    win.webContents.send('download:status', data);
  }
  return { success: true };
});
// 获取保存路径
ipcMain.handle('get-save-path', async () => {
  return secureStore.getPlain('savePath');
});
// 执行安装软件 - 高级进程跟踪
ipcMain.handle('install-software', async (event, data) => {
  return InstallSoftware(data, win);
});

// 添加检查文件是否存在的 IPC 处理程序
ipcMain.handle('check-file-exists', async (event, filePath) => {
  try {
    return fs.existsSync(filePath);
  } catch (error) {
    return false;
  }
});
// 获取应用图标的 IPC 处理程序
ipcMain.handle('get-app-icon', async (event, data) => {
  try {
    // let softIcon = secureStore.getPlain("softIcon");
    // const row = softIcon.filter(p => p.name && data.name.toLowerCase().indexOf(p.name.toLowerCase()) > -1);
    // if (row.length > 0) {
    //   return row[0].icon;
    // }
    logger.info(`获取应用图标: ${JSON.stringify(data)}`);
    if (!data.path || !fs.existsSync(data.path)) {
      return null;
    }

    // 使用已有的 icon-extractor 提取图标
    const baseName = path.basename(data.path, path.extname(data.path));

    // 每次都销毁旧实例
    CloseIconExtractorDestroy();

    // 强制重新 require，避免复用旧子进程
    delete require.cache[require.resolve('icon-extractor')];
    process.env.ICON_EXTRACTOR_PATH = getIconExtractorPath();
    iconExtractor = require('icon-extractor');
    iconExtractor.emitter.removeAllListeners('icon');

    return new Promise((resolve, reject) => {
      const onIcon = (data) => {
        iconExtractor.emitter.removeListener('icon', onIcon);
        if (data && data.Base64ImageData) {
          resolve(`data:image/png;base64,${data.Base64ImageData}`);
        } else {
          resolve(null);
        }
      };

      iconExtractor.emitter.once('icon', onIcon);

      iconExtractor.getIcon(baseName, appPath, (error, data) => {
        iconExtractor.emitter.removeListener('icon', onIcon);
        if (error) {
          console.error('提取图标失败:', error);
          resolve(null);
        } else {
          if (data && data.Base64ImageData) {
            resolve(`data:image/png;base64,${data.Base64ImageData}`);
          } else {
            resolve(null);
          }
        }
      });

      // 设置超时机制防止卡死
      setTimeout(() => {
        iconExtractor.emitter.removeListener('icon', onIcon);
        resolve(null);
      }, 5000);
    });
  } catch (error) {
    console.error('获取应用图标失败:', error);
    return null;
  }
});
//下载队列窗口
async function createDownloadWindow() {
  if (downloadWindow) {
    if (downloadWindow.isVisible()) {
      downloadWindow.hide(); // 如果窗口已经可见，则隐藏
    } else {
      downloadWindow.show(); // 如果窗口不可见，则显示
    }
    downloadWindow.focus();
    return;
  }
  downloadWindow = new BrowserWindow({
    width: 400,
    height: 600,
    resizable: false,
    frame: false, // 无边框，更像“面板”
    show: false, // 先不显示
    webPreferences: {
      contextIsolation: false,
      nodeIntegration: true,
      enableRemoteModule: false
    },
    // 放在右下角
    x: screen.getPrimaryDisplay().workAreaSize.width - 420,
    y: screen.getPrimaryDisplay().workAreaSize.height - 620
  });
  //downloadWindow.webContents.toggleDevTools();
  // 加载下载页面
  if (process.env.NODE_ENV === 'development') {
    downloadWindow.loadURL('http://localhost:8080/downloads');
  } else {
    logger.debug('加载下载页面');
    downloadWindow.loadFile('dist_electron/index.html', { hash: '/downloads' });
  }
  // 隐藏后不销毁，只隐藏
  downloadWindow.on('close', (e) => {
    if (!downloadWindow.forceClose) {
      e.preventDefault();
      downloadWindow.hide();
    }
  });
}
//下载页面显示
ipcMain.handle('show-download-panel', () => {
  if (downloadWindow) {
    if (!downloadWindow.isVisible()) {
      downloadWindow.show(); // 如果窗口不可见，则显示
    }
  } else {
    createDownloadWindow();
  }
});
// 下载页面隐藏
ipcMain.on('download:close', () => {
  if (downloadWindow) {
    downloadWindow.hide();
  }
});
//下载地址截取fileName
function getFileNameFromUrl(url) {
  const match = url.match(/[?&]fileName=([^&]*)/);
  if (match && match[1]) {
    return decodeURIComponent(match[1]); // 注意解码，如空格被编码为 %20
  }
  return null;
}
// IPC: 开始下载
ipcMain.handle('download:start', async (event, { id, url, softName }) => {
  if (downloadWindow) {
    if (!downloadWindow.isVisible()) {
      downloadWindow.show(); // 如果窗口不可见，则显示
    }
    return await createDownload(id, url, softName, `${secureStore.getPlain('savePath')}/${getFileNameFromUrl(url)}`, downloadWindow);
  } else {
    await createDownloadWindow();
    downloadWindow.webContents.on('did-finish-load', () => {
      createDownload(id, url, softName, `${secureStore.getPlain('savePath')}/${getFileNameFromUrl(url)}`, downloadWindow);
    });
    return { success: true };
  }
});
// IPC: 暂停下载（实际是取消，后续可支持断点续传）
ipcMain.handle('download:pause', async (event, id) => {
  return pauseDownload(id);
});
// IPC: 继续下载（⚠️ 简化版：重新开始，完整版需支持 Range 请求）
ipcMain.handle('download:resume', async (event, id) => {
  logger.info(`=== IPC 接收到 download:resume ===`);
  logger.info(`参数: id=${id}`);
  logger.info(`downloadWindow 状态: ${downloadWindow ? '存在' : '不存在'}`);

  if (!downloadWindow) {
    logger.error('downloadWindow 不存在');
    return { success: false, error: '下载窗口不存在' };
  }

  const result = await resumeDownload(id, downloadWindow);
  logger.info(`resumeDownload 返回结果:`, result);
  logger.info(`=== IPC 处理完成 download:resume ===`);
  return result;
});
// IPC: 删除/取消下载
ipcMain.handle('download:cancel', async (event, id) => {
  return cancelDownload(id);
});